<template>
	<view class="page-body">
		<link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet" />
		<!-- 页面内容开始 -->

		<!-- 表格搜索组件开始 -->
		<vk-data-table-query
			v-model="queryForm1.formData"
			:columns="queryForm1.columns"
			@search="search"
		></vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 自定义按钮区域开始 -->
		<view>
			<el-row>
				<el-button type="success" size="small" icon="el-icon-circle-plus-outline" @click="addBtn">添加</el-button>
				<!-- 批量操作 -->
				<el-dropdown v-if="table1.multipleSelection" :split-button="false"	trigger="click" @command="batchBtn">
					<el-button type="danger" size="small" style="margin-left: 20rpx;"
						:disabled="table1.multipleSelection.length === 0"
					>
						批量操作<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item :command="0">下线</el-dropdown-item>
						<el-dropdown-item :command="1">上线</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
			</el-row>
		</view>
		<!-- 自定义按钮区域结束 -->

		<!-- 表格组件开始 -->
		<vk-data-table
			ref="table1"
			:action="table1.action"
			:columns="table1.columns"
			:query-form-param="queryForm1"
			:right-btns="['detail_auto','update','delete']"
			:selection="true"
			:pagination="true"
			@update="updateBtn"
			@delete="deleteBtn"
			@current-change="currentChange"
			@selection-change="selectionChange"
		>
			<template v-slot:view_count="{ row, column, index }">
				<el-input v-model="row.view_count" size="mini" @change="viewCountChange($event, row)"/>
			</template>
		</vk-data-table>
		<!-- 表格组件结束 -->

		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-dialog
			v-model="form1.props.show"
			:title="form1.props.title"
			width="900px"
			mode="form"
			:close-on-click-modal="false"
		>
			<vk-data-form
				v-model="form1.data"
				:rules="form1.props.rules"
				:action="form1.props.action"
				:form-type="form1.props.formType"
				:columns='form1.props.columns'
				label-width="120px"
				:before-action="form1.props.beforeAction"
				@success="form1.props.show = false;refresh();"
			>
			<template v-slot:content="{ form, keyName }">
			   <div style="border: 1px solid #ccc;z-index:999">
				   <Toolbar
					   style="border-bottom: 1px solid #ccc"
					   :editor="editor"
					   :defaultConfig="vk.myfn.toolbarConfig()"
					   mode="default"
				   />
				   <Editor
					   style="height: 400px; overflow-y: hidden;"
					   v-model="form[keyName]"
					   :defaultConfig="vk.myfn.editorConfig('输入内容')"
					   mode="default"
					   @onCreated="onCreated"
				   />
			   </div>
			</template>
			</vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗结束 -->
		<view class="uni-im-chat-components" :hidden="!showAI">
		  <view class="close-bar">
		    <!-- <view class="head">
		      <text class="title">nineth-ai-chat</text>
		      <text class="desc">输入prompt提示词后AI根据你的输入生成文章</text>
		    </view> -->
		    <view class="close" @click="showAI=false">
		      <uni-icons type="closeempty" size="40rpx" class="icon"></uni-icons>
		    </view>
		  </view>
		  <aiChat ref="aiChat"></aiChat>
		</view>
		<!-- 页面内容结束 -->
	</view>
</template>

<script>
	import { nextTick } from "vue";
	var that;													// 当前页面对象
	var vk = uni.vk;									// vk实例
	var originalForms = {};						// 表单初始化数据
	import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
	import AiButtonMenu from "./components/editor-ai";
	import { Boot } from '@wangeditor/editor'
	import aiChat from "@/components/ai/chat"
	
	const aiConf = {
	  key: 'AI', 
	  factory() {
	    return new AiButtonMenu() 
	  },
	}
	
	Boot.registerMenu(aiConf)

	export default {
		data() {
			// 页面数据变量
			return {
				// 页面是否请求中或加载中
				loading:false,
				editor: null,
				showAI: false,
				// init请求返回的数据
				data:{

				},
				// 表格相关开始 -----------------------------------------------------------
				table1:{
					// 表格数据请求地址
					action:"admin/sys/ugc.getList",
					// 表格字段显示规则
					columns:[
						{ key:"_id", title:"id", type:"text", width:220 },
						{ key:"title", title:"标题", type:"text", width:120 },
						{ 
						  key: "", title: "用户信息", type: "group", width: 120, align:"left",
						  columns:[
							{ key: "userInfo._id", title: "ID", type: "text" },
							{ key: "userInfo.avatar", title: "头像", type: "avatar" },
							{ key: "userInfo.nickname", title: "昵称", type: "text" },
							{ key: "userInfo.username", title: "姓名", type: "text" },
						  ],
						},
						{ 
							key:"article_status", title:"文章状态", type:"switch", activeValue:1, inactiveValue: 2,
							watch:(res)=>{
								let { value, row, change } = res;
								vk.callFunction({
									url: "admin/sys/ugc.editUpdate",
									title: "请求中...",
									data: {
										_id: row._id,
										article_status: value
									},
									success: data => {
										if (data.num > 0) {
											change(value);
										}
									}
								});
							}
						},
						{ 
							key:"comment_status", title:"开放评论", type:"switch", activeValue:1, inactiveValue:0,
							watch:(res)=>{
								let { value, row, change } = res;
								vk.callFunction({
									url: "admin/sys/ugc.editUpdate",
									title: "请求中...",
									data: {
										_id: row._id,
										comment_status: value
									},
									success: data => {
										if (data.num > 0) {
											change(value);
										}
									}
								});
							}
						},
						{ 
							key:"is_essence", title:"是否加精", type:"switch", activeValue:true, inactiveValue:false,
							watch:(res)=>{
								let { value, row, change } = res;
								vk.callFunction({
									url: "admin/sys/ugc.editUpdate",
									title: "请求中...",
									data: {
										_id: row._id,
										is_essence: value
									},
									success: data => {
										if (data.num > 0) {
											change(value);
										}
									}
								});
							}
						},
						{ 
							key:"is_sticky", title:"是否置顶", type:"switch", activeValue:true, inactiveValue:false,
							watch:(res)=>{
								let { value, row, change } = res;
								vk.callFunction({
									url: "admin/sys/ugc.editUpdate",
									title: "请求中...",
									data: {
										_id: row._id,
										is_sticky: value
									},
									success: data => {
										if (data.num > 0) {
											change(value);
										}
									}
								});
							}
						},
						{ key:"location.merger_name", title:"所属区域", type:"text", width:160 },
						{ key:"view_count", title:"累计浏览量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"comment_count", title:"累计评论量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"collection_count", title:"累计收藏量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"like_count", title:"累计点赞量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key:"share_count", title:"累计分享量", type:"number", width:140, defaultValue:0, sortable:"custom" },
						{ key: "content", title: "内容", type: "html", show:["detail"] },
						{ key:"_add_time", title:"添加时间", type:"time", width:160 },
					],
					// 多选框选中的值
					multipleSelection:[],
					// 当前高亮的记录
					selectItem:""
				},
				// 表格相关结束 -----------------------------------------------------------
				// 表单相关开始 -----------------------------------------------------------
				// 查询表单请求数据
				queryForm1:{
					// 查询表单数据源，可在此设置默认值
					formData:{
						article_status: 1
					},
					// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
					columns:[
						{ key:"content", title:"内容", type:"text", width:160, mode:"%%" },
						{ 
							key:"article_status", title:"文章状态", type:"select", width:160, 
							data: [
								{ value: 0, label: "草稿箱" },
								{ value: 1, label: "已发布" },
								{ value: 2, label: "已下线" }
							]
						},
						{ key:"_add_time", title:"添加时间", type:"datetimerange", width:400, mode:"[]" },
						{
							key:"area_code", title:"所属区域", type:"remote-select", placeholder:"请选择区域" ,
							action:"admin/sys/zone.getListByName",
							props:{ list:"rows", value:"area_code", label:"merger_name" },
						},
						{
						  key:"category_ids", title:"分类", type:"remote-select", placeholder:"请选择分类", mode:"in",
						  multiple: true,
						  action:"admin/sys/category.getAdminList",
						  props:{ list:"rows", value:"_id", label:"name" },
						  showAll:true
						},
						// {
						//   key:"tags", title:"话题", type:"remote-select", placeholder:"请选择话题",
						//   action:"admin/sys/category.getTagsList",
						//   props:{ list:"rows", value:"_id", label:"name" },
						//   showAll: true,
						//   multiple: true
						// }
					]
				},
				form1:{
					// 表单请求数据，此处可以设置默认值
					data: {
						article_status: 1,
						comment_status: 1,
						is_essence: false,
						is_sticky: false,
						on_audio: false,
						location: uni.getStorageSync('location') || null,
						merger_name: uni.getStorageSync('location') ? uni.getStorageSync('location').merger_name : "",
						area_code: uni.getStorageSync('location') ? uni.getStorageSync('location').area_code : ""
					},
					// 表单属性
					props: {
						// 提交之前，需要处理一些数据
						// beforeAction:(formData)=>{
						//   // 将插入的视频占位全部修改为视频标签
						//   formData.content = vk.myfn.imgVideoTagTurn(formData.content, 0);
						//   return formData;
						// },
						// 表单请求地址
						action:"",
						// 表单字段显示规则
						columns:[
							{ key:"title", title:"标题", type:"text", placeholder:"请输入标题" },
							{ key:"avatar", title:"封面图", type:"image", limit:1 },
							{ key:"content", title: "内容", type: "editor" },
							{ key:"article_status", title:"文章状态", type:"switch", activeValue:1, inactiveValue:0, activeText: "发布", inactiveText: "草稿箱"},
							{
							  key:"category_ids", title:"分类", type:"remote-select", placeholder:"请选择分类",
							  action:"admin/sys/category.getAdminList",
							  props:{ list:"rows", value:"_id", label:"name" },
							  multiple: true,
							  showAll:true
							},
							{ key:"comment_status", title:"开放评论", type:"switch", activeValue:1, inactiveValue:0, activeText: "开发", inactiveText: "关闭"},
							{ key:"is_sticky", title:"是否置顶", type:"switch", activeValue:true, inactiveValue:false},
							{ key:"is_essence", title:"是否加精", type:"switch", activeValue:true, inactiveValue:false},
							{ key:"on_audio", title:"语音合成", type:"switch", activeValue:true, inactiveValue:false, tips: "开启之后将打开语音合成"},
							{ key:"is_site", title:"是否是站点", type:"switch", activeValue:true, inactiveValue:false, tips: "开启之后将生成站点，同时app进入也是站点"},
							{
								key:"area_code", title:"当前区域", type:"table-select", placeholder:"请选择区域" ,
								action:"admin/sys/zone.getList",
								pageSize: 10,
								columns: [
								    { key: "area_code", title: "区域id", type: "text" ,idKey: true},
								    { key: "merger_name", title: "区域全名", type: "text", nameKey: true}, // idKey:true 代表此字段为主键字段，若设置show:["none"],则可以在表格中隐藏该字段的显示
								    { key: "name", title: "区域简称", type: "text" }
								],
								queryColumns: [
								    { key: "merger_name", title: "区域名称", type: "text", width: 150, mode: "%%" },
								],
								onChange:(val, formData, column, index, option)=>{
									// 本地存下这次选择的值，下次就不用再选择了
									// 关闭之后，只清除当前的数据，但是不清除本地存储的
									if(val){
										uni.setStorageSync("location",option);							
										that.$nextTick(()=>{
											formData.location = option;
										})
									}else{
										that.$nextTick(()=>{
											formData.location = {};
										})
									}
									
								}
							},							
						],
						// 表单验证规则
						rules:{
							content: [
							  { required: true, message: '内容不能为空', trigger: 'blur' },
							]
						},
						// add 代表添加 update 代表修改
						formType:"",
						// 是否显示表单的弹窗
						show:false
					}
				},
				// 其他弹窗表单
				formDatas:{},
				// 表单相关结束 -----------------------------------------------------------
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
			uni.$on("openAI",(e)=>{
				that.showAI = true;
			})
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady() {},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options) {
				originalForms["form1"] = vk.pubfn.copyObject(that.form1);
			},
			// 页面跳转
			pageTo(path) {
				vk.navigateTo(path);
			},
			// 表单重置
			resetForm(){
				vk.pubfn.resetForm(originalForms, that);
			},
			// 搜索
			search(){
				that.$refs.table1.search();
			},
			// 刷新
			refresh(){
				that.$refs.table1.refresh();
			},
			// 获取当前选中的行的数据
			getCurrentRow(){
				return that.$refs.table1.getCurrentRow();
			},
			// 监听 - 行的选中高亮事件
			currentChange(val){
				that.table1.selectItem = val;
			},
			// 当选择项发生变化时会触发该事件
			selectionChange(list) {
				that.table1.multipleSelection = list;
			},
			// 显示添加页面
			addBtn(){
				that.resetForm();
				that.form1.props.action = 'admin/sys/ugc.add';
				that.form1.props.formType = 'add';
				that.form1.props.title = '添加';
				that.form1.props.show = true;
			},
			// 显示修改页面
			updateBtn({ item }){
				that.form1.props.action = 'admin/sys/ugc.update';
				that.form1.props.formType = 'update';
				that.form1.props.title = '编辑';
				that.form1.props.show = true;
				that.form1.data = item;
				if(vk.pubfn.isNotNull(item.location)){
					that.form1.data.merger_name = item.location.merger_name;
				}
			},
			// 删除按钮
			deleteBtn({ item, deleteFn }){
				deleteFn({
					action:"admin/sys/ugc.delete",
					data:{
						_id: item._id
					},
				});
			},
			// 监听 - 批量操作的按钮点击事件
			batchBtn(index){
				switch(index){
					//文章下架
					case 0: {
						this.changeStatus(0)
					}; break;
					case 1: {
						this.changeStatus(1)
					}; break;
					default : break;
				}
			},
			changeStatus(article_status){
				let _ids = [];
				that.table1.multipleSelection.map((item,index)=>{
					_ids.push(item._id);
				});
				
				vk.callFunction({
					url: 'admin/sys/ugc.batchAction',
					title:'请求中...',
					data:{
						_ids,
						article_status
					},
					success:function(data) {
						that.$notify({
							message:'批量操作成功!',
							type:'success'
						});
						that.refresh();
					}
				});
			},
			viewCountChange(count, item){
				vk.callFunction({
					url: 'admin/sys/ugc.updateViewCount',
					data: {
						_id: item._id,
						view_count: Number(count)
					},
					success: (data) => {
			
					}
				});
			},
			onCreated(editor) {
				this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
			},
			beforeDestroy() {
				const editor = this.editor
				if (editor == null) return
				editor.destroy() // 组件销毁时，及时销毁编辑器
				uni.$off("openAI");
			}
		},
		// 监听属性
		watch: {

		},
		// 过滤器
		filters: {

		},
		// 计算属性
		computed: {

		},
		components: {
			Toolbar,
			Editor,
			aiChat
		},
	};
</script>

<style lang="scss" scoped>
	.page-body {

	}
	.uni-im-chat-components {
	  width: 450px;
	  position: fixed;
	  right: 50px;
	  bottom: 0px;
	  // height: calc(100% - 70px);
	  z-index: 99999;
	  border: #fefefe solid 2px;
	  box-shadow: 0 0 10px rgba(0, 0, 0, .1);
	  border-radius: 8px;
	  overflow: hidden;
	
	  .close-bar {
	    height: 50px;
		width: 430px;
	    background: #fff;
	    display: flex;
	    align-items: center;
	    padding: 0 10px;
	    justify-content: flex-end;
	    position: absolute;
	
	    .head {
	      display: flex;
	      position: absolute;
	      left: 0;
	      right: 0;
	      text-align: center;
	      flex-direction: column;
	      gap: 5px;
	
	      .title {
	        font-size: 14px;
	        font-weight: bold;
	        color: #333;
	        padding-bottom: 0;
	        border: none;
	      }
	
	      .desc {
	        font-size: 12px;
	        color: #999;
	      }
	    }
	
	    .close {
	      width: 30px;
	      height: 30px;
	      background: #f1f1f1;
	      border-radius: 50%;
	      display: flex;
	      align-items: center;
	      justify-content: center;
	      position: relative;
	      z-index: 2;
	      cursor: pointer;
	
	      .icon {
	        display: block;
	      }
	    }
	  }
	
	  ::v-deep {
	    //* {
	    //  max-width: 100%;
	    //}
	
	    .page {
	      height: 720px;
	    }
	
	    .container {
	      width: 100%;
	      height: 100%;
	      margin: 0;
	      box-shadow: none;
	      flex: 1;
	      border-radius: 0;
	    }
	
	    .menu {
	      padding: 0;
	    }
	    .msg-item {
	      .content {
	        max-width: 88%;
	      }
	    }
	
	    .trash {
	      width: auto;
	    }
	
	    .foot-box {
	      gap: 10px;
	      padding: 10px;
	      .send {
	        width: 50px;
	      }
	      .textarea-box {
	        flex: 1;
	        width: auto;
	        .textarea {
	          width: 100%;
	        }
	      }
	    }
	  }
	}
	@media screen and (max-width: 768px) {
	  .uni-im-chat-components {
	    width: 100%;
	    left: 0;
	    right: 0;
	    bottom: 0;
	    margin: 0 auto;
	    border: none;
	
	    &:before {
	      content: "";
	      position: fixed;
	      top: 0;
	      left: 0;
	      right: 0;
	      bottom: 0;
	      background: rgba(0, 0, 0, .5);
	      z-index: -1;
	    }
	  }
	}
</style>
